<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>引出生命周期</title>
  <!--  引入React核心库-->
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <!--  引入react-dom,用于支持React操作Dom-->
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <!-- 引入babel，用于将jsx转为js-->
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script src="https://unpkg.com/prop-types@15.6.2/prop-types.js"></script>
</head>

<body>
  <!-- 准备一个容器 -->
  <div id="root"></div>
  <script type="text/babel">

    // 1.创建一个组件
    // 生命周期回调函数 <=>生命周期回调钩子 <=>生命周期函数 <=>生命周期钩子
    class Life extends React.Component {
      state = {
        opacity: 1
      }
      death = () => {
        // 清除定时器
        // clearInterval(this.timer)
        root.unmount(container)
      }
      // 组件挂载之后
      componentDidMount(){
        this.timer = setInterval(() => {
          // 获取原状态
          let { opacity } = this.state
          //减小0.1
          opacity -=0.1
          if (opacity <=0) opacity =1
          // 设置新的透明度
          this.setState({opacity})
        }, 200)
      }
      // 组件将要卸载
      componentWillUnmount(){
        // 清除定时器
        clearInterval(this.timer)
      }
      // render调用时机：初始化渲染，状态更新之后
      render() {
        return (
          <div>
            <h1 style={{ opacity: this.state.opacity }}>React学不会怎么办?</h1>
            <button onClick={this.death}>不活了</button>
          </div>
        )
      }
    }

    // 2.渲染组件到页面
    const container = document.getElementById('root')
    const root = ReactDOM.createRoot(container)
    root.render(<Life />)
  </script>
</body>

</html>